// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let godsMes = await db.collection('gods').where({
        _openid: wxContext.OPENID,
    }).get()
    let collect_list = godsMes.data[0].collect_list
    let arr = []
    if (event.list != undefined) {  //删除
        event.list.forEach(element => {
            for (const index in collect_list) {
                if (collect_list[index]._id != element) {
                    arr.push(collect_list[index])
                }
            }
        });

        await db.collection('gods').where({
            _openid: wxContext.OPENID,
        }).update({
            data: {
                collect_list: arr
            }
        })

        return "ok"
    } else {  //请求
        for (const index in collect_list) {
            let obj = {}
            obj.time = collect_list[index].time
            let goods = await db.collection('usedGoods_list').where({
                _id: collect_list[index]._id
            }).get()
            if (goods.data[0] != null) {
                obj.mes = goods.data[0]
            } else {
                obj.mes = {
                    intro: "该物品已下架",
                    title: "建议取消收藏",
                    images: ["https://7465-test-wz0tn-1301797917.tcb.qcloud.la/BYO/404.png?sign=60afeb7093d15ab90342479fd709f5e0&t=1589773111"],
                    _id: collect_list[index]._id
                }
            }

            arr.push(obj)
        }

        return arr

    }
}